import { Graph } from "@antv/x6";

/**
 * 节点数据类型定义
 */
export interface NodeData {
	id: string;
	shape: string;
	x: number;
	y: number;
	width?: number;
	height?: number;
	label?: string;
	attrs?: Record<string, any>;
	data?: Record<string, any>;
	[key: string]: any;
}

/**
 * 添加节点到图中
 * @param graph - X6 图实例
 * @param nodes - 节点数据数组
 * @returns 添加的节点 ID 数组
 */
export function addNodes(graph: Graph | null, nodes: NodeData[]): string[] {
	if (!graph) {
		console.error("Graph instance is null");
		return [];
	}

	const nodeIds: string[] = [];

	try {
		// 开始批量操作，提高性能
		graph.batchUpdate(() => {
			nodes.forEach(node => {
				const { id, shape, x, y, width = 100, height = 40, label = "", attrs = {}, ...rest } = node;
				// 创建节点配置
				const nodeConfig: any = {
					id,
					shape,
					x,
					y,
					width,
					height,
					attrs: {
						// 合并默认属性和用户提供的属性
						body: {
							stroke: "#5F95FF",
							strokeWidth: 1,
							fill: "#EFF4FF",
							...attrs.body
						},
						label: {
							text: label,
							fill: "#262626",
							fontSize: 12,
							...attrs.label
						},
						...attrs
					},
					...rest
				};

				// 根据形状类型处理特殊情况
				if (shape === "circle") {
					// 确保圆形节点的宽高相等
					const size = Math.max(width, height);
					nodeConfig.width = size;
					nodeConfig.height = size;
				} else if (shape === "polygon" && !attrs.body?.refPoints) {
					// 为多边形设置默认的参考点
					nodeConfig.attrs.body.refPoints = "0,0 100,0 100,100 0,100";
				}

				// 创建并添加节点
				const x6Node = graph.createNode(nodeConfig);
				const addedNode = graph.addNode(x6Node);
				nodeIds.push(addedNode.id);
			});
		});

		console.log(`Successfully added ${nodeIds.length} nodes`);
		return nodeIds;
	} catch (error) {
		console.error("Failed to add nodes:", error);
		return [];
	}
}

/**
 * 添加单个节点到图中
 * @param graph - X6 图实例
 * @param node - 节点数据
 * @returns 添加的节点 ID
 */
export function addNode(graph: Graph | null, node: NodeData): string | null {
	if (!graph) {
		console.error("Graph instance is null");
		return null;
	}

	try {
		const ids = addNodes(graph, [node]);
		return ids.length > 0 ? ids[0] : null;
	} catch (error) {
		console.error("Failed to add node:", error);
		return null;
	}
}
